#include "pciemsg.h"
#include <stdlib.h>

uint32_t fa_pcie_count_req_mem(uint32_t reqnum)
{
    return sizeof(fa_pcie_req_arr_t) + reqnum * sizeof(fa_pcie_req_t);
}

fa_pcie_req_arr_t* fa_pcie_apply_req_mem(uint32_t reqnum)
{
    uint32_t size = fa_pcie_count_req_mem(reqnum);
    void *header = malloc(size);
    if (header)
    {
        memset(header, 0, size);
    }
    return (fa_pcie_req_arr_t*)header;
}

void fa_pcie_free_req_mem(fa_pcie_req_arr_t *req)
{
    if (req)
    {
        free(req);
    }
}

void fa_pcie_set_reg2(fa_pcie_req_arr_t* arr, uint32_t reg, uint32_t value)
{
    arr->req[arr->reqnum].op          = FA_PCIE_SET;
    arr->req[arr->reqnum].addr_offset = reg;
    arr->req[arr->reqnum].value[0]    = value;
    arr->reqnum++;
}

void fa_pcie_get_reg2(fa_pcie_req_arr_t* arr, uint32_t reg, uint32_t *value)
{
    arr->req[arr->reqnum].op = FA_PCIE_GET;
    arr->req[arr->reqnum].addr_offset = reg;
    arr->reqnum++;
}

void fa_pcie_handle_msg(void* fd, zmq_msg_t* fromaddr, void* data, uint32_t size)
{
    fa_pcie_req_arr_t* req = (fa_pcie_req_arr_t *)data;
    uint32_t reqnum = req->reqnum;
    uint32_t idx;

    for (idx = 0; idx < reqnum; idx++)
    {
        fa_pcie_req_t* areq = &req->req[idx];
        if ((uint32_t)areq->op == (uint32_t)FA_PCIE_SET) 
        {
            //de
            continue;
        }
        if ((uint32_t)areq->op == (uint32_t)FA_PCIE_GET)
        {
            fa_pcie_rep_arr_t rep = { 0 };
            rep.reqnum = 1;
            rep.rep[0].op = FA_PCIE_GET;
            rep.rep[0].value[0] = 100;
            zmq_msg_send(fromaddr, fd, ZMQ_SNDMORE);
            zmq_send(fd, &rep, sizeof(fa_pcie_rep_arr_t), 0);
            //now only support one Get operation
            break;
        }
    }
}
